package com.sinya.shoppingmall.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sinya.shoppingmall.CommodityActivity;
import com.sinya.shoppingmall.R;
import com.sinya.shoppingmall.bean.Constants;
import com.sinya.shoppingmall.utils.IntoUtils;
import com.sinya.shoppingmall.utils.TouchUtils;
import com.sinya.shoppingmall.utils.UIUtils;
import com.sinya.shoppingmall.widget.ADCycleView;
import com.sinya.shoppingmall.widget.SearchView;
import com.sinya.shoppingmall.widget.scanner.FullScannerActivity;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 首页界面
 *
 * @author KoizumiSinya
 * @date 2015/12/24. 23:40
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private static final int ZXING_CAMERA_PERMISSION = 1;
    private Class<?> mClss;

    private TextView tv_title;
    private ADCycleView ADView;

    private SearchView searchView;
    private LinearLayout searchList;

    private PopupWindow menuPop;
    private static String[] menuList = {"扫一扫", "分享"};
    private static int[] menuResList = {R.mipmap.scanner, R.mipmap.share};

    // [+] Handler

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:

                    break;
                default:
                    break;
            }

            return false;
        }
    });

    // [-] Handler

    // [+] 继承自BaseFragment的方法

    @Override
    protected View initView() {
        return View.inflate(mContext, R.layout.fragment_one, null);
    }

    @Override
    protected void setView() {
        initADView();
        initSearchView();
        initSearchList();
        initRecommend();
    }

    @Override
    protected void setTitle() {
        tv_title = (TextView) rootView.findViewById(R.id.tv_title);
        tv_title.setText(mContext.getString(R.string.title_home));

        ImageView back = (ImageView) rootView.findViewById(R.id.img_back);
        back.setImageResource(R.drawable.title_back_image_selector);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);

        ImageView right = (ImageView) rootView.findViewById(R.id.img_right);
        right.setImageResource(R.drawable.title_right_image_selector);
        right.setVisibility(View.VISIBLE);
        right.setOnClickListener(this);

        /*ImageView scanner = (ImageView) rootView.findViewById(R.id.scan);
        scanner.setImageResource(R.mipmap.scan);
        scanner.setVisibility(View.VISIBLE);
        scanner.setOnClickListener(this);*/

    }

    @Override
    public void onResume() {
        searchView.initDefalutSearchView();
        super.onResume();
    }

    // [-] 继承自BaseFragment的方法
    // [+] 自定义初始化其它控件

    private void initADView() {
        ADView = (ADCycleView) rootView.findViewById(R.id.ad_view);

        //TODO 先模拟图片 以后通过请求网络获取
        int[] imagesRes = {R.mipmap.default_ad_image1, R.mipmap.default_ad_image2, R.mipmap.default_ad_image3,//
                R.mipmap.default_ad_image4, R.mipmap.default_ad_image5, R.mipmap.default_ad_image6};
        ADView.setImagesRes(imagesRes);

        //传入SlidingPaneLayout 在内部处理滑动冲突
        ADView.setSlideLayout(mSlidingPaneLayout);
    }

    private void initSearchView() {

        searchView = (SearchView) rootView.findViewById(R.id.search);
        searchView.setHideView(rootView.findViewById(R.id.title_layout), rootView.findViewById(R.id.ll_container), rootView.findViewById(R.id.ll_search), rootView);
        searchView.setSearchListener(new SearchView.onSearchInputListener() {
            @Override
            public void editTextChanged() {
                //TODO 输入搜索内容时需要匹配模糊查询内容
            }

            @Override
            public void onCancel() {
                //TODO 取消搜索
            }

            @Override
            public void onSearch() {
                //TODO 点击搜索
            }

            @Override
            public void onClickSearch() {

            }
        });
    }

    private void initSearchList() {
        searchList = (LinearLayout) rootView.findViewById(R.id.ll_search);
    }

    private void initRecommend() {
        LinearLayout ll_new = (LinearLayout) rootView.findViewById(R.id.ll_new);
        ll_new.setOnClickListener(this);
        TouchUtils.sideTouchLose(mSlidingPaneLayout, ll_new);

        LinearLayout ll_discount = (LinearLayout) rootView.findViewById(R.id.ll_discount);
        ll_discount.setOnClickListener(this);
        TouchUtils.sideTouchLose(mSlidingPaneLayout, ll_discount);

        LinearLayout ll_limit = (LinearLayout) rootView.findViewById(R.id.ll_limit);
        ll_limit.setOnClickListener(this);
        TouchUtils.sideTouchLose(mSlidingPaneLayout, ll_limit);

        LinearLayout ll_seasonal = (LinearLayout) rootView.findViewById(R.id.ll_seasonal);
        ll_seasonal.setOnClickListener(this);
        TouchUtils.sideTouchLose(mSlidingPaneLayout, ll_seasonal);

        LinearLayout ll_shop = (LinearLayout) rootView.findViewById(R.id.ll_shop);
        ll_shop.setOnClickListener(this);
        TouchUtils.sideTouchLose(mSlidingPaneLayout, ll_shop);
    }

    //[+] canner

    private void showScanner() {
        launchActivity(FullScannerActivity.class);
    }

    public void launchActivity(Class<?> clss) {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            mClss = clss;
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, ZXING_CAMERA_PERMISSION);
        } else {
            Intent intent = new Intent(mContext, clss);
            startActivity(intent);
        }
    }

    //[-] canner

    private void showShare() {
        ShareSDK.initSDK(mContext);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        //分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getString(R.string.share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        //oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(mContext);
    }

    /**
     * 显示popwindow 弹出拓展功能业务
     */
    private void showMenuPopWindow() {

        LinearLayout layout = (LinearLayout) View.inflate(mContext, R.layout.view_popwindow_menu, null);
        layout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                togglePopMenu();
                return false;
            }
        });
        final ListView menuList = (ListView) layout.findViewById(R.id.listview);
        menuList.setAdapter(new PopWindowMenuAdatper());
        menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    //扫一扫
                    case 0:
                        showScanner();
                        break;

                    //分享
                    case 1:
                        showShare();
                        break;
                    default:
                        break;
                }
                menuPop.dismiss();
                menuPop = null;
            }
        });

        menuPop = new PopupWindow(mContext);
        menuPop.setBackgroundDrawable(null);
        menuPop.setContentView(layout);
        menuPop.setOutsideTouchable(true);
        menuPop.setFocusable(true);
        menuPop.setWidth(UIUtils.getScreenWidth(getActivity()) * 3 / 10);
        menuPop.setHeight(400);
        menuPop.setAnimationStyle(R.style.popwindow_menu_style);
        menuPop.showAtLocation(rootView.findViewById(R.id.img_right), Gravity.RIGHT | Gravity.TOP, 5, rootView.findViewById(R.id.img_right).getBottom() * 5 / 3);
    }

    private void togglePopMenu() {
        if (menuPop != null && menuPop.isShowing()) {
            menuPop.dismiss();
        }
    }
    // [-] 自定义初始化其它控件
    // [+] 点击事件

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                if (mSlidingPaneLayout != null) {
                    mSlidingPaneLayout.openPane();
                }
                break;

            case R.id.img_right://TODO
                showMenuPopWindow();
                break;

            //新品
            case R.id.ll_new:
                CommodityDetail(Constants.NEW_SALE, "新品发布");
                break;

            //打折
            case R.id.ll_discount:
                CommodityDetail(Constants.DISCOUNT, "促销打折");
                break;

            //限时抢购
            case R.id.ll_limit:
                CommodityDetail(Constants.PANIC_BUYING, "限时抢购");
                break;

            //换季降价
            case R.id.ll_seasonal:
                CommodityDetail(Constants.SEASONAL, "换季降价");
                break;

            //专柜
            case R.id.ll_shop:
                CommodityDetail(Constants.BRAND, "正品专柜");
                break;

            default:
                break;
        }
    }

    // [-] 点击事件

    /**
     * 进入模块内容
     */
    private void CommodityDetail(int id, String title) {
        Bundle bundle = new Bundle();
        bundle.putString(Constants.BUNDLE_FIELD_TITLE, title);
        bundle.putInt(Constants.BUNDLE_FIELD_INDEX, id);
        IntoUtils.goActivity(mContext, bundle, CommodityActivity.class);
    }

    // [+] Class

    private class PopWindowMenuAdatper extends BaseAdapter {

        @Override
        public int getCount() {
            return menuList.length;
        }

        @Override
        public String getItem(int position) {
            return menuList[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(mContext, R.layout.view_popwindow_menu_item, null);
            TextView textView = (TextView) convertView.findViewById(R.id.tv_name);
            textView.setText(menuList[position]);
            ImageView img = (ImageView) convertView.findViewById(R.id.img_icon);
            img.setImageResource(menuResList[position]);
            return convertView;
        }
    }

    // [-] Class
}
